﻿using DongFangGuoKai.TaskPlatform.Commn.ApiModule;
using DongFangGuoKai.TaskPlatform.Commn.ApiModule.Dto;
using DongFangGuoKai.TaskPlatform.Commn.Attributes;
using DongFangGuoKai.TaskPlatform.Commn.ConfigureOptions;
using DongFangGuoKai.TaskPlatform.Commn.LogModule;
using DongFangGuoKai.TaskPlatform.Job.WarehousingReturn.Dto;
using DongFangGuoKai.TaskPlatform.Job.WarehousingReturn.Model;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Quartz;
using RestSharp;
using SqlSugar;

namespace DongFangGuoKai.TaskPlatform.Job.WarehousingReturn
{
    [Job("入库任务", "入库回传", "入库回传任务3分钟执行一次")]
    public class WarehousingReturnJob : IJob
    {
        public IApiClient _apiClient { get; set; }
        public IOptions<UrlConfigOption> _urlOption { get; set; }
        public LogHelper<WarehousingReturnJob> _log { get; set; }

        public SyncIDType _syncID = SyncIDType.WarehousingOut;

        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                UrlConfigOption? urlConfigOption = _urlOption.Value;
                string url = Path.Combine(urlConfigOption.WMSPDAUrl, JobHelper.GetWMSSuffixUrl(_syncID));
                var result = _apiClient.Get<ApiDataResult<JToken>>(url);

                if (result.Code != 200)
                {
                    _log.LogError(url, null, result.Msg, result.Code.ToString());
                    await Task.CompletedTask;
                    return;
                }
                if (!result.Data.Any())
                {
                    await Task.CompletedTask;
                    return;
                }
                var data = result.Data.ToObject<WarehousingReturnModel>();
                #region v1.  实体字段一样，简化 
                WarehousingReturnDto warehousingDto = new WarehousingReturnDto()
                {
                    CheckNumber = data.CheckNumber,
                    StoreId = data.StoreId,
                    UserId = data.UserId
                };
                bool isExitItem = data.Items != null && data.Items.Count > 0;
                Parameter[] paraS = new Parameter[isExitItem ? 2 : 1];
                paraS[0] = new QueryParameter("CheckNumber", data.CheckNumber);
                if (isExitItem)
                {
                    int?[] orderIds = new int?[data.Items.Count];
                    warehousingDto.Items = new();
                    for (int i = 0; i < data.Items.Count; i++)
                    {
                        warehousingDto.Items.Add(new WarehousingReturnDetailDto
                        {
                            Count = data.Items[i].Count,
                            RelationId = data.Items[i].RelationId,
                            StoreLocationId = data.Items[i].StoreLocationId,
                            Remark = data.Items[i].Remark
                        });
                        orderIds[i] = data.Items[i].OrderId;

                    }
                    paraS[1] = new QueryParameter("OrderIds", string.Join(',', orderIds));

                }
                #endregion


                string postUrl = Path.Combine(urlConfigOption.HaiNingUrl, JobHelper.GetHHSuffixUrl(_syncID));
                var res = _apiClient.Post<ApiResultData>(postUrl, warehousingDto);
                if (res.Code != "200")
                {
                    _log.LogError(postUrl, JsonConvert.SerializeObject(warehousingDto), res.Msg);
                    await Task.CompletedTask;
                    return;
                }

                string putUrl = Path.Combine(urlConfigOption.WMSPDAUrl, "TReceivingBill/UpdateReceivingBillStatus");

                var putRes = _apiClient.Put<ApiDataResult<object>>(putUrl, paraS);
                if (putRes.Code != 200)
                {
                    _log.LogError(putUrl, paraS.ToString(), "入库状态回传失败，详情:" + putRes.Msg, putRes.Code.ToString());
                    await Task.CompletedTask;
                    return;
                }
                _log.LogSuc(postUrl, JsonConvert.SerializeObject(data));

            }
            catch (Exception ex)
            {
                _log.LogCtmError(ex.Message);
            }
            await Task.CompletedTask;
        }
    }
}
